package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/shop/configuration"
	"kop/modules/shop/entity"
	"kop/util/date"
	"time"
)

func AutoMigrate(dB *gorm.DB) {

	dB.AutoMigrate(new(entity.Shop))
	dB.AutoMigrate(new(entity.ShopGoods))
}

func GetShop(dB *gorm.DB, roleID, shopID int32) *entity.Shop {

	var conf, err = configuration.GetShopByShopID(shopID)
	if err != nil {
		panic(err)
	}

	var data = &entity.Shop{
		RoleID:     roleID,
		ShopID:     shopID,
		RefreshNum: conf.Refresh.Limit,
		Version:    conf.Refresh.Version,
	}

	data.CDStart()

	if err = dB.FirstOrCreate(data).Error; err != nil {
		panic(err)
	}

	if date.Date(time.Now()) != date.Date(data.UpdatedAt) {
		data.RefreshNum = conf.Refresh.Limit
	}

	return data
}

func SaveShop(dB *gorm.DB, data *entity.Shop) {

	if err := dB.Save(data).Error; err != nil {
		panic(err)
	}
}
